const form = document.getElementById('form');
const account = document.getElementById('account');
const password = document.getElementById('password');

// 获取字段的名字
function getFieldName(input) {
    switch (input) {
        case account:
            return '账号';
        case password:
            return '密码';
        default:
            return '';
    }
}

// 展示错误信息
function showError(input, message) {
    const formControl = input.parentElement;
    formControl.className = 'form-control error';
    const small = formControl.querySelector('small');
    small.innerText = message;
}

// 展示成功信息
function showSuccess(input) {
    const formControl = input.parentElement;
    formControl.className = 'form-control success';
}

// 检查输入长度
function checkLength(input, min, max) {
    if (input.value.length < min) {
        showError(
            input,
            `${getFieldName(input)}至少是${min}个字符`
        );
        return false;
    } else if (input.value.length > max) {
        showError(
            input,
            `${getFieldName(input)}最多是${max}个字符`
        );
        return false;
    } else {
        showSuccess(input);
        return true;
    }
}

// 检查是否全是数字
function checkDigit(input) {
    const re = /^\d+$/;
    if (re.test(input.value.trim())) {
        showSuccess(input);
        return true;
    } else {
        showError(input, `${getFieldName(input)}必须是数字`);
        return false;
    }
}

// 检查必填选项是否填写
function checkRequired(input) {
    if (input.value.trim() === '') {
        showError(input, `请输入${getFieldName(input)}`);
        return false;
    } else {
        showSuccess(input);
        return true;
    }
}

// 检查输入是否合法
function check() {
    let ret = true;
    ret &= checkRequired(account) && checkDigit(account);
    ret &= checkRequired(password) && checkLength(password, 6, 25);
    return ret;
}

// 登录失败之后的提示
function loginFailed() {
    showError(account, '账号或密码错误');
    showError(password, '账号或密码错误');
}

// 表单提交时触发的事件
form.addEventListener('submit', function (e) {
    e.preventDefault();

    if (!check())
        return;

    // 发送post请求
    let url = "/login-api";
    let obj = {
        "account": account.value,
        "password": password.value,
    };
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(obj)
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok: ' + response.statusText);
        }
        return response.json();
    }).then(data => {
        window.location.href = data.returnAddress;
    }).catch(error => {
        loginFailed();
        console.error('There has been a problem with your fetch operation:', error);
    });

});
